#!/usr/bin/env python3
"""
使用浏览器会话访问Ford API获取完整Key Features
通过Selenium执行JavaScript来获取API数据
"""

import sys
import os
sys.path.append(os.path.dirname(os.path.abspath(__file__)))

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from webdriver_manager.chrome import ChromeDriverManager
import time
import json

def fetch_apis_with_browser():
    """使用浏览器会话获取API数据"""
    
    chrome_options = Options()
    chrome_options.add_argument('--no-sandbox')
    chrome_options.add_argument('--disable-dev-shm-usage')
    chrome_options.add_argument('--disable-gpu')
    chrome_options.add_argument('--window-size=1920,1080')
    # chrome_options.add_argument('--headless')
    
    service = Service(ChromeDriverManager().install())
    driver = webdriver.Chrome(service=service, options=chrome_options)
    
    try:
        print("🔍 使用浏览器会话获取Ford API数据...")
        
        # 先访问主页面建立会话
        url = "https://www.ford.co.uk/shop/build-your-ford/ngc2/ice2/model?catalogId=WAEGB-CGE-2022-FocusMCAGBR202450&series=ACMAA_VS-DH&planId=c"
        print(f"🌐 访问主页面建立会话: {url}")
        
        driver.get(url)
        
        # 等待页面加载
        WebDriverWait(driver, 15).until(
            EC.presence_of_element_located((By.CSS_SELECTOR, 'div[data-cy][class*="ProductTile"]'))
        )
        
        # 处理Cookie
        try:
            cookie_buttons = driver.find_elements(By.CSS_SELECTOR, 'button[id*="cookie"], button[class*="cookie"]')
            for btn in cookie_buttons:
                if btn.is_displayed():
                    btn.click()
                    time.sleep(2)
                    break
        except:
            pass
        
        print("✅ 主页面会话已建立")
        
        # 关键API端点
        apis = [
            {
                'name': 'Vehicle Model Load (Titanium)',
                'url': 'https://www.servicescache.ford.com/api/vehicle-model/v1/load?locale=en_GB&retrieve=images,specs,featuresMkt,selectedMkt,featureImages,featureSpecs,keyFeatures,keyFeaturesModel,keyFeaturesWalkup,uscCodes,prices,featurePrices,content,packages&feature=&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-DH&displayContext=VISTA&suppressDisplayContext=true&namedConfig=default'
            },
            {
                'name': 'Vehicle Model Describe (All Configs)',
                'url': 'https://www.servicescache.ford.com/api/vehicle-model/v1/describe?locale=en_GB&retrieve=images,specs,featuresMkt,selectedMkt,featureImages,featureSpecs,keyFeatures,keyFeaturesModel,keyFeaturesWalkup,uscCodes,prices,featurePrices,content,packages&feature=&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-DH&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-JY&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-D4&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-D5&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-D3&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMAA_VS-EC&config=WAEGB-CGE-2022-FocusMCAGBR202450~ACMHQ_VS-EC&displayContext=VISTA&suppressDisplayContext=true&namedConfig=default'
            }
        ]
        
        successful_apis = []
        
        for i, api in enumerate(apis):
            print(f"\n🌐 获取API {i+1}: {api['name']}")
            
            try:
                # 使用简化的JavaScript fetch
                print("🔄 执行fetch请求...")
                
                result = driver.execute_async_script(f"""
                    var callback = arguments[arguments.length - 1];
                    var url = '{api['url']}';
                    
                    fetch(url, {{
                        method: 'GET',
                        headers: {{
                            'Accept': 'application/json',
                            'Content-Type': 'application/json'
                        }}
                    }})
                    .then(function(response) {{
                        if (response.ok) {{
                            return response.json();
                        }} else {{
                            throw new Error('HTTP ' + response.status);
                        }}
                    }})
                    .then(function(data) {{
                        callback(data);
                    }})
                    .catch(function(error) {{
                        callback({{ error: error.toString() }});
                    }});
                """)
                
                if 'error' in result:
                    print(f"❌ API请求失败: {result['error']}")
                else:
                    print(f"✅ API请求成功，数据大小: {len(str(result))} 字符")
                    
                    # 搜索Key Features
                    data_str = json.dumps(result, ensure_ascii=False).lower()
                    
                    # 检查关键特性
                    expected_features = [
                        "alloy wheels",
                        "touchscreen",
                        "keyless",
                        "led headlamps", 
                        "quickclear",
                        "driver assistance",
                        "led rear lights",
                        "electrically operated",
                        "grille",
                        "dual-zone",
                        "sensico",
                        "parking sensors",
                        "lane-keeping",
                        "pre-collision",
                        "thatcham"
                    ]
                    
                    found_features = [f for f in expected_features if f in data_str]
                    
                    print(f"🎯 找到的Key Features关键词: {len(found_features)}/{len(expected_features)}")
                    print(f"   匹配的关键词: {found_features}")
                    
                    if len(found_features) > 3:
                        print(f"🎉 发现有价值的API数据！")
                        
                        successful_apis.append({
                            'name': api['name'],
                            'url': api['url'],
                            'data': result,
                            'found_features': found_features
                        })
                        
                        # 保存详细数据
                        filename = f"./release/browser_api_{i+1}_{api['name'].replace(' ', '_').replace('(', '').replace(')', '')}.json"
                        with open(filename, 'w', encoding='utf-8') as f:
                            json.dump({
                                'api_name': api['name'],
                                'api_url': api['url'],
                                'found_features': found_features,
                                'response_data': result
                            }, f, ensure_ascii=False, indent=2)
                        
                        print(f"💾 API数据已保存到: {filename}")
                    
            except Exception as e:
                print(f"❌ 获取API失败: {e}")
            
            time.sleep(2)
        
        # 深入分析成功的API
        if successful_apis:
            print(f"\n🎉 成功获取 {len(successful_apis)} 个API的数据！")
            
            for i, api in enumerate(successful_apis):
                print(f"\n📊 分析API {i+1}: {api['name']}")
                data = api['data']
                
                # 查找KeyFeatures相关的数据结构
                def find_key_features(obj, path="", results=None):
                    if results is None:
                        results = []
                    
                    if isinstance(obj, dict):
                        for key, value in obj.items():
                            key_lower = key.lower()
                            
                            # 寻找Key Features相关的键
                            if any(kw in key_lower for kw in ['keyfeature', 'feature', 'equipment', 'spec']):
                                results.append({
                                    'path': f"{path}.{key}",
                                    'key': key,
                                    'value': value,
                                    'type': type(value).__name__
                                })
                            
                            find_key_features(value, f"{path}.{key}", results)
                    
                    elif isinstance(obj, list):
                        for idx, item in enumerate(obj):
                            find_key_features(item, f"{path}[{idx}]", results)
                    
                    return results
                
                feature_paths = find_key_features(data)
                
                print(f"找到 {len(feature_paths)} 个可能的特性数据路径:")
                
                # 显示最有希望的路径
                for j, fp in enumerate(feature_paths[:5]):
                    print(f"  {j+1}. 路径: {fp['path']}")
                    print(f"     键名: {fp['key']}")
                    print(f"     类型: {fp['type']}")
                    
                    if isinstance(fp['value'], list):
                        print(f"     数组长度: {len(fp['value'])}")
                        if fp['value']:
                            print(f"     首个元素: {str(fp['value'][0])[:100]}...")
                    elif isinstance(fp['value'], dict):
                        keys = list(fp['value'].keys())[:3]
                        print(f"     对象键: {keys}")
                    else:
                        print(f"     值: {str(fp['value'])[:100]}...")
                
                # 特别查找Titanium的完整Key Features
                print(f"\n🔍 特别查找Titanium的Key Features...")
                
                # 搜索包含"titanium"和"ACMAA_VS-DH"的数据
                def find_titanium_features(obj, path=""):
                    results = []
                    
                    if isinstance(obj, dict):
                        # 检查这个对象是否与Titanium相关
                        obj_str = json.dumps(obj).lower()
                        if ('titanium' in obj_str or 'acmaa_vs-dh' in obj_str) and 'feature' in obj_str:
                            results.append({
                                'path': path,
                                'data': obj
                            })
                        
                        for key, value in obj.items():
                            results.extend(find_titanium_features(value, f"{path}.{key}"))
                    
                    elif isinstance(obj, list):
                        for idx, item in enumerate(obj):
                            results.extend(find_titanium_features(item, f"{path}[{idx}]"))
                    
                    return results
                
                titanium_features = find_titanium_features(data)
                
                if titanium_features:
                    print(f"🎯 找到 {len(titanium_features)} 个Titanium相关的特性数据!")
                    
                    for k, tf in enumerate(titanium_features[:3]):
                        print(f"\nTitanium特性数据 {k+1}:")
                        print(f"路径: {tf['path']}")
                        
                        # 尝试提取具体的特性列表
                        data_obj = tf['data']
                        if isinstance(data_obj, dict):
                            for feature_key in ['keyFeatures', 'features', 'equipment', 'specifications']:
                                if feature_key in data_obj:
                                    features = data_obj[feature_key]
                                    print(f"找到特性列表 '{feature_key}': {type(features).__name__}")
                                    
                                    if isinstance(features, list):
                                        print(f"特性数量: {len(features)}")
                                        for l, feature in enumerate(features[:10]):
                                            print(f"  {l+1}. {feature}")
                                    elif isinstance(features, dict):
                                        print(f"特性对象键: {list(features.keys())}")
                else:
                    print(f"❌ 未找到Titanium特定的特性数据")
            
            # 保存分析结果总结
            summary = {
                'successful_apis_count': len(successful_apis),
                'apis': [
                    {
                        'name': api['name'],
                        'url': api['url'],
                        'found_features_count': len(api['found_features']),
                        'found_features': api['found_features']
                    } for api in successful_apis
                ]
            }
            
            with open('./release/browser_api_analysis.json', 'w', encoding='utf-8') as f:
                json.dump(summary, f, ensure_ascii=False, indent=2)
            
            print(f"\n💾 浏览器API分析结果已保存到: ./release/browser_api_analysis.json")
            
        else:
            print(f"\n❌ 未能通过浏览器获取有价值的API数据")
        
    except Exception as e:
        print(f"❌ 浏览器API获取过程中出现异常: {e}")
        import traceback
        traceback.print_exc()
        
    finally:
        print("🧹 清理资源...")
        driver.quit()

if __name__ == "__main__":
    fetch_apis_with_browser()
